<template>
  <el-dialog
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      :status-icon="true"
      label-width="80px"
    >
      <el-form-item
        v-if="user.level < 3"
        label="所属村"
        prop="village"
      >
        <el-cascader
          v-model="form.villageWrap"
          :options="villageCascader"
          :props="villageProp"
          placeholder="请选择所属村"
          clearable
          @change="change"
        />
      </el-form-item>
      <el-form-item
        label="名称"
        prop="name"
      >
        <el-input
          v-model.trim="form.name"
          placeholder="请输入资产类型名称"
          clearable
          autocomplete="off"
        />
      </el-form-item>
    </el-form>
    <div
      slot="footer"
      class="dialog-footer"
    >
      <el-button @click="close">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="save"
      >
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "TableEdit",
  props: ["fetchData"],
  data() {
    return {
      form: {
        name: "",
        village: "",
        villageWrap: [],
      },
      id: null,
      created: true,
      rules: {
        name: [{ required: true, trigger: "blur", message: "请输入资产类型名称" }],
        village: [{ required: true, trigger: "change", message: "请选择资产类型所属村" }],
      },
      title: "",
      dialogFormVisible: false,
      villageCascader: [],
      villageProp: {
        value: "id",
        label: "name",
      },
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  created() {
    this.init()
  },
  methods: {
    async showEdit(row) {

      if (!row) {
        this.title = "添加";
        this.created = true;
      } else {
        this.id = row.id;
        const res = await this.$http.get(`assets-type/${this.id}?join=village`);

        const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

        const area = await this.$http.get(`town/${town.data.town.id}?join=area`);
        res.data.villageWrap = [area.data.area.id, town.data.town.id, res.data.village.id];
        this.title = "编辑";

        this.form = Object.assign({}, res.data);
        this.created = false;
      }
      this.dialogFormVisible = true;
    },
    close() {
      let { village } = this.form
      this.$refs["form"].resetFields();
      this.form = this.$options.data().form;
      this.dialogFormVisible = false;
      if(this.user.level == 3) {
        this.form.village = village
      }
    },
    save() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.created) {
            this.create();
          } else {
            this.edit();
          }
        } else {
          return false;
        }
      });
    },
    async create() {
      const res = await this.$http.post(`/assets-type`, this.form);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$emit("fetchData");
        this.close()
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      const res = await this.$http.put(`/assets-type/${this.id}`, this.form);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$emit("fetchData");
        this.close()
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.form));
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.form.village = val[val.length - 1];
    },

    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
         //村级
        this.form.village = this.user.village.id
      } 
    },
  },
};
</script>
